package pr.lanmu.service;


import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pr.lanmu.config.util.Current;
import pr.lanmu.config.util.Res;
import pr.lanmu.config.web.CustomException;
import pr.lanmu.controller.request.SQLReq;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;

@Service
public class SQLService {
    @Autowired
    private DataSource dataSource;

    @SneakyThrows
    public Res<?> execute(SQLReq.execute param) {
        executeSql(param.getSql());
        return Res.success();
    }

    @SneakyThrows
    public void executeSql(String sql) {
        if (!Current.getUser().getAdmin()) throw new CustomException("仅管理员可操作");
        Connection connection = dataSource.getConnection();
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.execute();
        ps.close();
        connection.close();
    }
}
